# -*- coding:utf-8 -*-
import re, random
from . import api
from flask import request, abort, current_app, jsonify, make_response, json
from iHome.utils.captcha.captcha import captcha
from iHome import redis_store
from iHome import constants
from iHome.utils.response_code import RET
from iHome.utils.sms import CCP
from iHome.models import User

@api.route("/sms", methods=['POST'])
def send_sms():
    """
    发送短信验证码
    1. 获取参数
    2. 验证参数是否有值
    3. 验证手机号是否合法
    4. 验证图片验证码是否正确
    5. 如果正确，删除本地图片验证码
    6. 生成短信验证码，并发送短信
    7. 给出响应
    :return:
    """

    # 1. 获取参数
    # mobile = request.args.get("mobile")
    # image_code = request.args.get("image_code")
    # image_code_id = request.args.get("image_code_id")
    # 1. POST方式获取数据
    data_dict = json.loads(request.data)
    mobile = data_dict.get("mobile")
    image_code = data_dict.get("image_code")
    image_code_id = data_dict.get("image_code_id")

    # 2. 验证参数是否有值
    if not all([image_code, image_code_id, mobile]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 验证手机号是否合法
    if not re.match(r"^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")

    # 4. 验证图片验证码是否正确
    # 4.1 取出保存的图片验证码内容
    try:
        real_image_code = redis_store.get("ImageCode_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据异常")

    # 4.2 判断是否有值，如果没有值代表已过期
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码过期")

    # 4.3 对比验证码
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")

    # 5. 如果正确，删除本地图片验证码
    try:
        redis_store.delete("ImageCode_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)

    # 5.1 判断手机号是否注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
    else:
        if user:
            return jsonify(errno=RET.DATAEXIST, errmsg="该手机号已注册")

    # 6. 生成短信验证码.
    sms_code = "%06d" % random.randint(0, 1000000)
    current_app.logger.debug("短信验证码为：%s" % sms_code)

    # 6.1 发送短信
    # sms_code_result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], '1')
    # if sms_code_result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信验证码失败")

    # 7. 保存短信验证码
    try:
        redis_store.set('SMS_' + mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="短信验证码保存错误")

    return jsonify(errno=RET.OK, errmsg="发送成功")


@api.route("/imagecode")
def get_image_code():
    """图片验证码生成"""

    # 1. 取到图片编码
    args = request.args
    cur = args.get("cur")
    pre = args.get("pre")

    # 判断参数是否有值
    if not cur:
        abort(403)

    # 生成图片 验证码
    _, text, image = captcha.generate_captcha()

    current_app.logger.debug("图片验证码为：%s" % text)

    try:
        if pre:
            # 删除之前的数据
            redis_store.delete("ImageCode_" + pre)
        # 将 cur_id 与图片验证码内容保存到本地
        redis_store.set("ImageCode_" + cur, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存图片验证码失败")

    # 设置响应
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"

    return response






